package org.spiderflow.mailbox.executor.shape;

import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.mailbox.utils.MailboxUtils;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

@Component
public class MailboxExecutor implements ShapeExecutor {

	public static final String MAILBOX_HOST = "host";

	public static final String MAILBOX_PORT = "port";

	public static final String MAILBOX_USERNAME = "username";

	public static final String MAILBOX_PASSWORD = "password";

	public static final String MAILBOX_TIMEOUT = "timeout";

	public static final String MAILBOX_CONTEXT_KEY = "$mailbox_";

	@Override
	public String supportShape() {
		return "mailbox";
	}

	@Override
	public Shape shape() {
		Shape shape = new Shape();
		// web界面上显示的图标
		shape.setImage("");
		// 拖放至容器里时默认的节点名称
		shape.setLabel("电子邮箱");
		// 模板文件名
		shape.setName("mailbox");
		// 鼠标移动至图标上显示的名称
		shape.setTitle("电子邮箱");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		String host = node.getStringJsonValue(MAILBOX_HOST);
		int port = NumberUtils.toInt(node.getStringJsonValue(MAILBOX_PORT), 25);
		String username = node.getStringJsonValue(MAILBOX_USERNAME);
		String password = node.getStringJsonValue(MAILBOX_PASSWORD);
		int timeout = NumberUtils.toInt(node.getStringJsonValue(MAILBOX_TIMEOUT), 60000);
		JavaMailSenderImpl mailboxTemplate = MailboxUtils.createMailSender(host, port, username, password, timeout);
		context.put(MAILBOX_CONTEXT_KEY + node.getNodeId(), mailboxTemplate);
	}

}
